package com.kakaxi.mybilibili.module.user.view;

import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.czy1121.view.RoundButton;
import com.kakaxi.mybilibili.R;
import com.kakaxi.mybilibili.base.MyApplication;
import com.kakaxi.mybilibili.base.NavigationActivity;
import com.kakaxi.mybilibili.bean.MemberBean;
import com.kakaxi.mybilibili.common.WebUrlConst;
import com.kakaxi.mybilibili.module.all.WebViewActivity;
import com.kakaxi.mybilibili.module.user.presenter.ILoginPresenter;
import com.kakaxi.mybilibili.module.user.presenter.LoginPresenter;
import com.kakaxi.mybilibili.utils.ProgressDialogUtil;

import java.util.Map;

import butterknife.BindColor;
import butterknife.BindDrawable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnFocusChange;
import butterknife.OnTextChanged;

/**
 * 登录活动类
 * Created by kakaxi on 16/12/1.
 */

public class LoginActivity extends NavigationActivity implements ILoginView {

    /** 活动请求码 **/
    public static final int ACT_REQUEST_CODE = 1000;

    @BindView(R.id.edt_login_username)
    EditText usernameEdt;
    @BindView(R.id.edt_login_password)
    EditText passwordEdt;
    @BindView(R.id.edt_login_captcha_input)
    EditText captchaEdt;

    @BindView(R.id.roubtn_login_action)
    RoundButton loginBtn;

    @BindView(R.id.img_login_logo_left)
    ImageView leftImg;
    @BindView(R.id.img_login_logo_right)
    ImageView rightImg;
    @BindView(R.id.img_login_captcha_pic)
    ImageView captchaImg;

    @BindDrawable(R.drawable.ic_login_username_default)
    Drawable usernameDrawable;
    @BindDrawable(R.drawable.ic_login_password_default)
    Drawable passwordDrawable;

    @BindDrawable(R.drawable.ic_22)
    Drawable leftShowDrawable;
    @BindDrawable(R.drawable.ic_33)
    Drawable rightShowDrawable;
    @BindDrawable(R.drawable.ic_22_hide)
    Drawable leftHideDrawable;
    @BindDrawable(R.drawable.ic_33_hide)
    Drawable rightHideDrawable;

    @BindColor(R.color.colorPrimary)
    int primaryColor;

    private ILoginPresenter mPresenter;

    private Bitmap mCaptchaBitmap;

    @Override
    protected int getCurrentMenuItemId() {
        return R.menu.menu_nav;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    protected void setupViews() {
        ButterKnife.bind(this);
        showBackBtn();
        setLoginBtnEnabled(false);
    }

    @Override
    protected void initData() {
        mPresenter = new LoginPresenter(this);
        mPresenter.initLogin(this);
    }

    /**
     * 把登录按钮设置为不可用
     */
    private void setLoginBtnEnabled(boolean isEnabled) {
        if (isEnabled) {
            loginBtn.getBackground().setColorFilter(null);
        } else {
            // 登录按钮遮罩层
            loginBtn.getBackground().setColorFilter(0x64ffffff, PorterDuff.Mode.ADD);
        }
        loginBtn.setEnabled(isEnabled);
    }

    /**
     * 请求验证码图片
     */
    private void getCaptchaImage() {
        if (mCaptchaBitmap != null) {
            mCaptchaBitmap.isRecycled();
            mCaptchaBitmap = null;
            captchaImg.setImageBitmap(null);
        }
        mPresenter.getCaptchaImage();
    }


    @OnFocusChange({
            R.id.edt_login_username,
            R.id.edt_login_password,
            R.id.edt_login_captcha_input
    })
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.edt_login_username:
                setEditDrawableColor(usernameDrawable, hasFocus);
                if (hasFocus) setLogoLeftRight(true);
                break;
            case R.id.edt_login_password:
                setEditDrawableColor(passwordDrawable, hasFocus);
                if (hasFocus) setLogoLeftRight(false);
                break;
            case R.id.edt_login_captcha_input:
                setLogoLeftRight(true);
                break;
        }
    }

    /**
     * 设置文本编辑器的选中图标颜色
     *
     * @param editDrawable 图标
     * @param hasFocus     是否已经获取焦点
     */
    private void setEditDrawableColor(Drawable editDrawable, boolean hasFocus) {
        if (hasFocus) {
            editDrawable.setColorFilter(primaryColor, PorterDuff.Mode.SRC_ATOP);
        } else {
            editDrawable.setColorFilter(null);
        }
    }

    /**
     * 设置logo左右边的图片
     *
     * @param isShow 是否睁开眼睛
     */
    private void setLogoLeftRight(boolean isShow) {
        if (isShow) {
            leftImg.setImageDrawable(leftShowDrawable);
            rightImg.setImageDrawable(rightShowDrawable);
        } else {
            leftImg.setImageDrawable(leftHideDrawable);
            rightImg.setImageDrawable(rightHideDrawable);
        }
    }


    @OnTextChanged(value = {
            R.id.edt_login_username,
            R.id.edt_login_password,
            R.id.edt_login_captcha_input
    }, callback = OnTextChanged.Callback.TEXT_CHANGED)
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // 当所有文本输入框都有文本就会让登录按钮可用
        setLoginBtnEnabled(isAllEditWithText());
    }

    /**
     * 判断是否所有输入框都有文本
     *
     * @return 是否都存在文本
     */
    private boolean isAllEditWithText() {
        return usernameEdt.length() != 0 && passwordEdt.length() != 0 && captchaEdt.length() != 0;
    }

    @OnEditorAction(R.id.edt_login_captcha_input)
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == 6 && isAllEditWithText()) {
            doLogin();
        }
        return false;
    }


    @OnClick({
            R.id.roubtn_login_action,
            R.id.roubtn_login_register,
            R.id.img_login_captcha_pic
    })
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.roubtn_login_register: {
                Bundle bundle = new Bundle();
                bundle.putString(WebViewActivity.EXTRA_URL, WebUrlConst.LOGIN_REGISTER_URL);
                bundle.putString(WebViewActivity.EXTRA_TITLE, "注册帐号");
                goActivity(WebViewActivity.class, bundle);
                break;
            }
            case R.id.roubtn_login_action: {
                doLogin();
                break;
            }
            case R.id.img_login_captcha_pic: {
                getCaptchaImage();
                break;
            }
        }
    }

    /**
     * 登录操作
     */
    private void doLogin() {
        mPresenter.doLogin(usernameEdt.getText().toString(),
                passwordEdt.getText().toString(),
                captchaEdt.getText().toString());
    }

    @Override
    public void setCaptchaImage(Bitmap captchaBitmap) {
        mCaptchaBitmap = captchaBitmap;
        captchaImg.setImageBitmap(mCaptchaBitmap);
    }

    @Override
    public void onCaptchaFailed() {
        showMessage("获取验证码失败...");
    }

    @Override
    public void showInitLoading() {
        ProgressDialogUtil.show(this);
    }

    @Override
    public void hideInitLoading() {
        ProgressDialogUtil.hide();
    }

    @Override
    public void initComplete(boolean isSuc) {
        if (isSuc) {
            getCaptchaImage();
        } else {
            showMessage("初始化失败!");
            finish();
        }
    }

    @Override
    public void saveLoginCookie(String userId, Map<String, String> cookieMap) {
        ((MyApplication) getApplication()).saveUserCookie(cookieMap);
        MemberBean memberBean = new MemberBean();
        memberBean.setMid(userId);
        ((MyApplication) getApplication()).setMemberBean(memberBean);
    }

    @Override
    public void saveUserInfo(MemberBean memberBean) {
        if (memberBean != null) {
            ((MyApplication) getApplication()).setMemberBean(memberBean);
            setResult(RESULT_OK);
        } else {
            setResult(RESULT_CANCELED);
        }
        showMessage("登录成功");
        finish();
    }

    @Override
    public void showLoading() {
        ProgressDialogUtil.show(this);
        ProgressDialogUtil.progressDialog.setMessage("登录中...");
    }

    @Override
    public void hideLoading() {
        ProgressDialogUtil.hide();
    }

    @Override
    public void showEmptyView() {

    }

    @Override
    public void showMessage(String message) {
        toastHandler(message);
    }
}
